extends Control
#定义信号
signal dialogue_finished 
signal expression_requested(expression_name: String) 
signal dialogue_started
#引用节点
@onready var name_label = $DialogueBox/NameLabel
@onready var content_label = $DialogueBox/ContentLabel
@onready var typing_sound = $TypingSound

#变量定义
var current_lines: Array = []
var current_index: int = 0
var is_active: bool = false
var current_tween: Tween #动画补间
var _last_visible_chars: int = 0
#打字速度
var typing_speed: float = 0.08

#主角配置
@export var player_name: String = "Memorica"
@export var player_color: Color = Color("00ffff")

#配角名单字典
var extra_characters: Dictionary = {
	"Yaochi": { "name": "yaochi", "color": Color("ff83ff") },
	"Gogue": { "name": "gogue", "color": Color.BLACK },
	"Voiceover": {"name": "", "color": Color.WEB_GRAY}
}

#暂存当前客人的信息
var temp_customer_name: String = ""
var temp_customer_color: Color = Color.WHITE

func _ready():
	hide()
	mouse_filter = Control.MOUSE_FILTER_IGNORE
	Dialogic.timeline_ended.connect(_on_timeline_ended)

func _process(_delta):
	# 只有当对话框显示时才检测
	if visible and content_label.visible_ratio < 1.0:
		# 获取当前实际显示的字符数
		var current_chars = content_label.visible_characters
		
		# 如果当前显示的字数 比 上一帧多 (说明刚打出了新字)
		if current_chars > _last_visible_chars:
			
			if current_chars <= content_label.text.length():
				var char_just_typed = content_label.text[current_chars - 1]
				
				# 只有不是空格的时候，才响
				if char_just_typed != " ":
					_play_random_pitch_sound()
			
			# 更新记录
			_last_visible_chars = current_chars

#播放随机音调的函数
func _play_random_pitch_sound():
	#检查有没有音频资源，防止报错
	if typing_sound.stream:
		#随机改变音调 (0.9 到 1.1 之间)
		#这样同一个音效听起来会有细微差别，像真实的打字声
		typing_sound.pitch_scale = randf_range(0.9, 1.1)
		typing_sound.play()

func _on_timeline_ended():
	print("对话结束，隐藏 DialogueLayer") #调试信息
	hide()
	
	dialogue_finished.emit()

#开始对话函数
func start_dialogue(character_name: String, lines: Array, character_color: Color = Color.WHITE):
	dialogue_started.emit()
	show()
	current_lines = lines
	current_index = 0
	
	#记录当前客人的信息
	temp_customer_name = character_name
	temp_customer_color = character_color
		
	is_active = true
	Global.set_interactive(false) #锁住操作
	
	show_next_line()
	
	

func show_next_line():
	#检查是否还有下一句
	if current_index < current_lines.size():
		var text_to_show = current_lines[current_index]
		current_index += 1
		#处理表情标签
		var exp_start = text_to_show.find("[exp=")
		if exp_start != -1:
			var exp_end = text_to_show.find("]", exp_start)
			if exp_end != -1:
				#提取表情名字
				var exp_name = text_to_show.substr(exp_start + 5, exp_end - exp_start - 5)
				#发送信号让Customer换脸
				expression_requested.emit(exp_name)
				
				#从显示的文本里删掉标签
				var tag_string = "[exp=" + exp_name + "]"
				text_to_show = text_to_show.replace(tag_string, "")
		
		#处理说话人
		if text_to_show.begins_with("[me]"):
			name_label.text = player_name
			name_label.modulate = player_color
			text_to_show = text_to_show.replace("[me]", "")
			
		#如果是配角
		elif _check_is_extra_character(text_to_show):
			var result = _process_extra_character(text_to_show)
			name_label.text = result["name"]
			name_label.modulate = result["color"]
			text_to_show = result["text"]
			
		#如果都不是，那就是当前客人说话
		else:
			name_label.text = temp_customer_name
			name_label.modulate = temp_customer_color
		

		#显示文本与播放打字机动画
		content_label.text = text_to_show
		
		#重置计数器
		content_label.visible_characters = 0 
		_last_visible_chars = 0
		
		#动态计算时间
		var duration = text_to_show.length() * typing_speed
		
		#创建并播放动画
		if current_tween: current_tween.kill()
		current_tween = create_tween()
		current_tween.tween_property(content_label, "visible_ratio", 1.0, duration)
	else:
		#没有下一句了，结束对话
		end_dialogue()

#结束对话
func end_dialogue():
	hide()
	is_active = false
	if Global: # 加上判断防止报错
		Global.set_interactive(true) 
	print("UI层：发出对话结束信号...")
	dialogue_finished.emit() #通知外部

#输入处理
func _input(event):
	if not is_active: return
	
	if event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
		get_viewport().set_input_as_handled()
		
		#检查字打完了没？
		if content_label.visible_ratio < 1.0:
			#没打完瞬间显示全部
			if current_tween: current_tween.kill()
			content_label.visible_ratio = 1.0
		else:
			#打完了显示下一句
			show_next_line()

#检查是否是配角
func _check_is_extra_character(text: String) -> bool:
	for tag in extra_characters:
		if text.begins_with("[" + tag + "]"):
			return true
	return false

#处理配角数据
func _process_extra_character(text: String) -> Dictionary:
	for tag in extra_characters:
		var tag_code = "[" + tag + "]"
		if text.begins_with(tag_code):
			var info = extra_characters[tag]
			return {
				"name": info["name"],
				"color": info["color"],
				"text": text.replace(tag_code, "")
			}
	return {}
